package com.senditcertified.mail;

import java.io.Reader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.simple.JSONValue;

import android.R.bool;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.Utility.GetEpackge;
import com.Utility.Message_Bean;
import com.Utility.UserTokenExpire;
import com.Utility.Utility;
import com.activities.SecureActivity;
import com.activities.group.TabBaseGroupActivity;
import com.google.gson.JsonObject;
import com.senditcertified.mail.R;
import com.parser.Deliver_Beans;
import com.parser.Error_Report;
import com.parser.Parser_Soap;
import com.senditcertified.mail.Message_Viewer.GetEPackage;
import com.soap.call.Http_Soap_Call;

public class Inbox extends Activity {
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	String Username = "";
	String Password = "";
	ProgressDialog pd;
	ArrayList<Message_Bean> Bean_List = new ArrayList<Message_Bean>();
	ListView list;
	MyListAdapter adapter;
	boolean isFile_Attached = false;
	boolean isSound_Attached = false;
	boolean isVideo_Attached = false;
	Spinner myspinner, year;
	public CheckBox only_New;
	String Month = "jan";
	String Year = "2013";
	String User_TOken = " ";
	String ONLYNEW = "true";
	String MSG_ID = null;
	String Year_[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
			"11" };
	int position = -1;

	SharedPreferences preferences;

	boolean isDate, isDiscription, isAttachment, isSender, isStatus = false;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		View contentView = LayoutInflater.from(getParent()).inflate(
				R.layout.inbox, null);
		setContentView(contentView);
		list = (ListView) findViewById(R.id.list);

		adapter = new MyListAdapter(getParent(), Bean_List);
		list.setAdapter(adapter);

		myspinner = (Spinner) findViewById(R.id.spnrmonths);
		year = (Spinner) findViewById(R.id.spnryear);
		ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
				this, R.array.months, R.layout.spinner);
		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		myspinner.setAdapter(adapter2);

		/*
		 * ArrayAdapter<CharSequence>
		 * adapter1=ArrayAdapter.createFromResource(getParent(), R.array.year,
		 * android.R.layout.simple_spinner_item);
		 * adapter.setDropDownViewResource
		 * (android.R.layout.simple_spinner_dropdown_item);
		 */

		ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
				this, R.array.year, R.layout.spinner);
		adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		year.setAdapter(adapter1);

		// year.setAdapter(adapter1);
		only_New = (CheckBox) findViewById(R.id.only_New);
		// Utility.setStringPreference(Password.this, "WEB", password
		// .getText().toString());
		// Utility.setStringPreference(Password.this, "WEB", Username);

		// TODO Put your code here
		Username = Utility.getStringPreference(getParent(), "username", "#");
		Password = Utility.getStringPreference(getParent(), "password", "#");
		Utility.printLog("Usrname", Username);
		Utility.printLog("Password", Password);

		getYear_Month();

		list.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				MSG_ID = Bean_List.get(arg2).getMsg_guid();
				position = arg2;

				if (Bean_List.get(arg2).getActions().equals("R")) {
					startActivity(new Intent(Inbox.this, RecallActivity.class));
				} else if (Bean_List.get(arg2).getActions().equals("T")) {
					new GetDeliveryAcceptance().execute(
							Utility.getStringPreference(getParent(),
									"LoginToken", ""), Bean_List.get(arg2)
									.getMsg_guid());
				} else if (Bean_List.get(arg2).getActions().equals("V")) {
					new GetEPackage().execute(Utility.getStringPreference(
							getParent(), "LoginToken", ""), MSG_ID, "");
				}

			}
		});

		// "LoginToken", 1 + ""), "true", "11", "2011", repor),repor);
		Button view_Message = (Button) findViewById(R.id.view_Message);
		view_Message.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				/*
				 * if (only_New.isChecked() == true) { getYear_Month(); //
				 * Month=myspinner.getSelectedItem().toString(); //
				 * Year=year.getSelectedItem().toString(); new
				 * User_GetUserInbox().execute(Password); //
				 * Toast.makeText(getParent(), //
				 * "Please unselect the check box", //
				 * Toast.LENGTH_SHORT).show(); } else {
				 */

				Month = Integer.parseInt(Year_[myspinner
						.getSelectedItemPosition()]) + 1 + "";

				Year = year.getSelectedItem().toString();
				new User_GetUserInbox().execute(Password);
				// }
			}
		});

		only_New.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if (isChecked) {
					ONLYNEW = "true";
				} else {
					ONLYNEW = "false";
				}
			}
		});

		Button date_time = (Button) findViewById(R.id.date_time);
		Button description = (Button) findViewById(R.id.description);
		Button attaachment = (Button) findViewById(R.id.attaachment);
		Button sender = (Button) findViewById(R.id.sender);
		Button status = (Button) findViewById(R.id.status);

		date_time.setOnClickListener(new OnClickListener() {

			@SuppressWarnings("unchecked")
			public void onClick(View v) {

				Collections.sort(Bean_List, new Comparator<Message_Bean>() {

					public int compare(Message_Bean lhs, Message_Bean rhs) {
						// TODO Auto-generated method stub

						String first = lhs.getDateAndTime();

						System.out.println("Date " + first);

						String Second = rhs.getDateAndTime();

						Date Date1 = null;
						Date Date2 = null;

						try {
							DateFormat df = new SimpleDateFormat("MM/dd/yyyy");

							Date1 = df.parse(first);
							Date2 = df.parse(Second);
						} catch (Exception e) {
							e.printStackTrace();
						}

						if (!isDate) {
							isDate = true;
							return (Date1).compareTo(Date2);

						} else {
							isDate = false;
							return (Date2).compareTo(Date1);
						}
					}
				});
				adapter.notifyDataSetChanged();
				if (Bean_List != null && Bean_List.size() != 0)
					isDate = true;
			}
		});

		description.setOnClickListener(new OnClickListener() {

			@SuppressWarnings("unchecked")
			public void onClick(View v) {

				Collections.sort(Bean_List, new Comparator<Message_Bean>() {

					public int compare(Message_Bean lhs, Message_Bean rhs) {
						// TODO Auto-generated method stub
						String first = lhs.getDescription();
						String Second = rhs.getDescription();
						if (!isDiscription) {
							isDiscription = true;
							return (first).compareTo(Second);

						} else {
							isDiscription = false;
							return (Second).compareTo(first);
						}
					}
				});
				adapter.notifyDataSetChanged();

			}
		});

		attaachment.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				Collections.sort(Bean_List, new Comparator<Message_Bean>() {

					public int compare(Message_Bean lhs, Message_Bean rhs) {
						// TODO Auto-generated method stub
						String first = lhs.getAttachments();
						String Second = rhs.getAttachments();

						if (!isAttachment) {
							isAttachment = true;
							return (first).compareTo(Second);

						} else {
							isAttachment = false;
							return (Second).compareTo(first);
						}
					}
				});
				adapter.notifyDataSetChanged();

			}
		});

		sender.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				Collections.sort(Bean_List, new Comparator<Message_Bean>() {

					public int compare(Message_Bean lhs, Message_Bean rhs) {
						// TODO Auto-generated method stub
						String first = lhs.getSender();
						String Second = rhs.getSender();

						if (!isSender) {
							isSender = true;
							return (first).compareTo(Second);

						} else {
							isSender = false;
							return (Second).compareTo(first);
						}
					}
				});
				adapter.notifyDataSetChanged();

			}
		});

		status.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				Collections.sort(Bean_List, new Comparator<Message_Bean>() {

					public int compare(Message_Bean lhs, Message_Bean rhs) {
						// TODO Auto-generated method stub
						String first = lhs.getStatus();
						String Second = rhs.getStatus();

						if (!isStatus) {
							isStatus = true;
							return (first).compareTo(Second);

						} else {
							isStatus = false;
							return (Second).compareTo(first);
						}
					}
				});
				adapter.notifyDataSetChanged();

			}
		});
		if (User_TOken.equals(" ")) {
			new User_Token_Task().execute(Password);
		}

	}

	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();

	}

	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}

	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// if(Bean_List!=null && Bean_List.size()!=0){
		list.setSelection(0);
		// }

	}

	public class GetEPackage extends AsyncTask<String, Void, Boolean> {
		boolean result = false;
		// String error_msg = "";
		String Result = null;
		Parser_Soap parse = new Parser_Soap();
		Error_Report repor = new Error_Report();

		protected Boolean doInBackground(String... params) {
			Http_Soap_Call call = Http_Soap_Call.create_connection("",
					getParent());
			if (call != null) {
				// Result = parse.GetLoginToken(
				// call.GetLoginToken(Username, params[0], repor), repor);
				Result = parse.GetEPackage(call.GetEPackage(params[0],
						params[1], params[2], repor), repor);
				if (Result != null) {
					result = true;

				} else {
					// error_msg=Utility.INVALID_USER;
					System.out.println("false");
					result = false;
					repor.setMessage("Internal Error");
				}

			} else {
				repor.setMessage(Utility.NETWORK_ISSUE);
				return false;
			}

			return result;
		}

		protected void onPreExecute() {
			pd = ProgressDialog.show(getParent(), null,
					getString(R.string.loader));
		}

		protected void onPostExecute(Boolean result) {
			// This method runs in the UI thread

			pd.dismiss();
			if (result) {
				// Utility.printLog("Login Responce", "Login successfully");
				// Utility.setStringPreference(getParent(), "LoginToken",
				// Result);
				System.out.println("Parse Result");
				parse_GetEpackage(Result);

			} else {
				// Utility.printLog("Login Responce", "Login Unsuccessfully");
				// Toast.makeText(Password.this, repor.getMessage(),
				// Toast.LENGTH_SHORT).show();
			}

		}
	}

	private void getYear_Month() {
		// TODO Auto-generated method stub
		SimpleDateFormat dateformate = new SimpleDateFormat("dd-MM-yyyy");
		Calendar currentDate = Calendar.getInstance();

		String currentDateStr = dateformate.format(currentDate.getTime());
		// Log.i("Infoe ", " " + currentDateStr.toString());
		System.out.println("Current date is :  " + currentDateStr);
		// //=== OR

		SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

		sdf.applyPattern("dd-MM-yyyy");
		Date x = new Date(currentDate.get(Calendar.YEAR) - 1900,
				currentDate.get(Calendar.MONTH),
				currentDate.get(Calendar.DAY_OF_MONTH));
		// Log.i("Infoe ", " " + sdf.format(x));
		System.out.println(sdf.format(x));
		String YEAR_MONTH[] = sdf.format(x).split("-");
		Month = YEAR_MONTH[1];
		Year = YEAR_MONTH[2];

		myspinner.setSelection((Integer.parseInt(Month) - 1));

	}

	public void parse_GetEpackage(String result) {
		try {
			// JSONArray aaray = new JSONArray(result);
			GetEpackge getEpackge = null;

			// for (int i = 0; i < aaray.length(); i++) {

			JSONObject jobj = new JSONObject(result);

			getEpackge = new GetEpackge();

			getEpackge.setFile_create(jobj.getString("file_create"));
			getEpackge.setFile_desc(jobj.getString("file_desc"));
			getEpackge.setUsername(jobj.getString("username"));
			getEpackge.setFirst_name(jobj.getString("first_name"));
			getEpackge.setLast_name(jobj.getString("last_name"));

			getEpackge.setFile_msg(jobj.getString("file_msg"));

			if (jobj.has("file_name1")) {
				getEpackge.setFile_name(jobj.getString("file_name1"));
			}

			getEpackge.setFile_name2(jobj.getString("file_name2"));
			getEpackge.setFile_name3(jobj.getString("file_name3"));
			getEpackge.setFile_name4(jobj.getString("file_name4"));
			getEpackge.setFile_name5(jobj.getString("file_name5"));
			getEpackge.setFile_name6(jobj.getString("file_name6"));

			getEpackge.setFile_name7(jobj.getString("file_name7"));
			getEpackge.setFile_name8(jobj.getString("file_name8"));
			getEpackge.setFile_name9(jobj.getString("file_name9"));
			getEpackge.setFile_name10(jobj.getString("file_name10"));
			getEpackge.setVoice_msg(jobj.getString("voice_msg"));
			System.out.println("voice_msg" + jobj.getString("voice_msg") + "");
			getEpackge.setVideo_msg(jobj.getString("video_msg"));
			System.out.println("video_msg" + jobj.getString("video_msg") + "");
			getEpackge.setUser_id(jobj.getString("user_id"));
			getEpackge.setUpload_dir(jobj.getString("upload_dir"));
			getEpackge.setCollaboration(jobj.getString("collaboration"));
			getEpackge.setSend_to(jobj.getString("send_to"));
			getEpackge.setNo_download(jobj.getString("no_download"));
			getEpackge.setNo_forward(jobj.getString("no_forward"));

			getEpackge.setNo_print(jobj.getString("no_print"));
			getEpackge.setAdd_watermark(jobj.getString("add_watermark"));
			getEpackge.setAllow_view(jobj.getString("allow_view"));

			// }
			if (getEpackge != null) {
				Intent intent = new Intent(getParent(),
						SecureActivity.class);
				intent.putExtra("Message", getEpackge);
				intent.putExtra("MSG_ID", MSG_ID);
				((TabBaseGroupActivity) getParent()).startChildActivity(
						SecureActivity.class.getSimpleName(), intent);

			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public class MyListAdapter extends BaseAdapter {

		private Context context;
		private ArrayList<Message_Bean> myList;
		private LayoutInflater li;

		public MyListAdapter(Context c, ArrayList<Message_Bean> mesaage) {
			context = c;
			myList = mesaage;
			li = LayoutInflater.from(c);
		}

		public int getCount() {
			return myList.size();
		}

		public Object getItem(int position) {
			return myList.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			final int pos = position;

			View view = li.inflate(R.layout.inbox_list_row, null);
			TextView text = (TextView) view.findViewById(R.id.Date);
			text.setText(myList.get(pos).getDateAndTime());
			TextView message = (TextView) view.findViewById(R.id.message);
			message.setText(myList.get(pos).getDescription());

			TextView name = (TextView) view.findViewById(R.id.name);
			name.setText(myList.get(pos).getSender());

			TextView file = (TextView) view.findViewById(R.id.file);
			TextView sound = (TextView) view.findViewById(R.id.sound);
			TextView video = (TextView) view.findViewById(R.id.video);
			TextView pending = (TextView) view.findViewById(R.id.status_img);

			if (myList.get(pos).getAttachments().equals("F")) {
				file.setVisibility(View.VISIBLE);
				sound.setVisibility(View.INVISIBLE);
				video.setVisibility(View.INVISIBLE);
			} else if (myList.get(pos).getAttachments().contains("FV")) {
				file.setVisibility(View.VISIBLE);
				sound.setVisibility(View.INVISIBLE);
				video.setVisibility(View.VISIBLE);
			}

			else if (myList.get(pos).getAttachments().contains("FSV")) {
				file.setVisibility(View.VISIBLE);
				sound.setVisibility(View.VISIBLE);
				video.setVisibility(View.VISIBLE);
			} else if (myList.get(pos).getAttachments().contains("SV")) {
				file.setVisibility(View.INVISIBLE);
				sound.setVisibility(View.VISIBLE);
				video.setVisibility(View.VISIBLE);
			} else if (myList.get(pos).getAttachments().equals("V")) {
				file.setVisibility(View.INVISIBLE);
				sound.setVisibility(View.INVISIBLE);
				video.setVisibility(View.VISIBLE);
			} else if (myList.get(pos).getAttachments().equals("")) {
				file.setVisibility(View.INVISIBLE);
				sound.setVisibility(View.INVISIBLE);
				video.setVisibility(View.INVISIBLE);
			}

			else if (myList.get(pos).getAttachments().equals("S")) {
				file.setVisibility(View.INVISIBLE);
				sound.setVisibility(View.VISIBLE);
				video.setVisibility(View.INVISIBLE);
			}

			Log.e("Status ", "" + myList.get(pos).getActions());
			if ((myList.get(pos).getActions().equals("V"))) {
				pending.setBackgroundResource(R.drawable.green_deliver);
			} else if ((myList.get(pos).getActions().equals("T"))) {
				pending.setBackgroundResource(R.drawable.blue_pending);
			} else if ((myList.get(pos).getActions().equals("R"))) {
				pending.setBackgroundResource(R.drawable.orange_recall);
			}
			return view;

		}
	}

	

	class User_Token_Task extends AsyncTask<String, Void, Boolean> {
		boolean result = false;
		// String error_msg = "";
		String Result = null;
		Parser_Soap parse = new Parser_Soap();
		Error_Report repor = new Error_Report();

		protected Boolean doInBackground(String... params) {
			Http_Soap_Call call = Http_Soap_Call.create_connection("",
					getParent());
			if (call != null) {
				Result = parse.GetLoginToken(
						call.GetLoginToken(Username, params[0], repor), repor);
				if (Result != null) {
					System.out.println("true");
					if (Result.contains("Password Error")) {
						result = false;
					} else {
						result = true;
					}

				} else {
					// error_msg=Utility.INVALID_USER;
					System.out.println("false");
					result = false;
					repor.setMessage("Internal Error");
				}

			} else {
				repor.setMessage(Utility.NETWORK_ISSUE);
				return false;
			}

			return result;
		}

		protected void onPreExecute() {
			pd = ProgressDialog.show(getParent(), null,
					getString(R.string.loader));
		}

		protected void onPostExecute(Boolean result) {
			// This method runs in the UI thread

			pd.dismiss();
			System.out.println("Parse Result::" + Result);
			if (result) {
				System.out.println("Parse Result::" + Result);
				try {
					JSONObject js = new JSONObject(Result);
					// JSONObject obj=js.getJSONObject(0);
					Result = js.getString("ReturnValue");

					Utility.setStringPreference(getParent(), "LoginToken",
							Result);

					getYear_Month();

					new User_GetUserInbox().execute(Password);
				} catch (Exception e) {
					e.printStackTrace();
					Toast.makeText(getParent(), "Token expired",
							Toast.LENGTH_LONG).show();
					finish();
				}
				/*
				 * Intent mainIntent = new Intent(Password.this,
				 * TabHome_Activity.class);
				 * Password.this.startActivity(mainIntent);
				 * Password.this.finish();
				 */
				// Toast.makeText(Password.this, "Login token get",
				// Toast.LENGTH_SHORT)
				// .show();
			} else {
				// Utility.printLog("Login Responce", "Login Unsuccessfully");
				// Toast.makeText(Password.this, repor.getMessage(),
				// Toast.LENGTH_SHORT).show();
			}

		}
	}

	public class User_GetUserInbox extends AsyncTask<String, Void, Boolean> {
		boolean result = false;
		// String error_msg = "";
		String Result = null;
		Parser_Soap parse = new Parser_Soap();
		Error_Report repor = new Error_Report();

		protected Boolean doInBackground(String... params) {
			Http_Soap_Call call = Http_Soap_Call.create_connection("",
					getParent());
			if (call != null) {
				// Result = parse.GetLoginToken(
				// call.GetLoginToken(Username, params[0], repor), repor);
				Result = parse.GetUserInbox(call.GetUserInbox(
						Utility.getStringPreference(getParent(), "LoginToken",
								1 + ""), only_New.isChecked() + "", Month,
						Year, repor), repor);
				if (Result != null) {
					result = true;

				} else {
					// error_msg=Utility.INVALID_USER;
					System.out.println("false");
					result = false;
					repor.setMessage("Internal Error");
				}

			} else {
				repor.setMessage(Utility.NETWORK_ISSUE);
				return false;
			}

			return result;
		}

		protected void onPreExecute() {
			pd = ProgressDialog.show(getParent(), null,
					getString(R.string.loader));
			System.out.println("IIR" + year.getSelectedItemPosition());
			System.out.println("myspinner" + year.getSelectedItemPosition());
			System.out.println("IIR" + only_New.isChecked());

			Utility.setIntPreference(getApplicationContext(), "year",
					year.getSelectedItemPosition());
			Utility.setIntPreference(getApplicationContext(), "month",
					myspinner.getSelectedItemPosition());
			Utility.setBooleanPreference(getApplicationContext(), "check",
					only_New.isChecked());

			System.out.println("ffff"
					+ Utility.getIntPreference(getApplicationContext(), "year",
							0));
			System.out.println("ffff"
					+ Utility.getIntPreference(getApplicationContext(),
							"month", 0));
			System.out.println("ffff"
					+ Utility.getBooleanPreference(getApplicationContext(),
							"check", true));

		}

		protected void onPostExecute(Boolean result) {
			// This method runs in the UI thread

			pd.dismiss();
			if (result) {
				// Utility.printLog("Login Responce", "Login successfully");
				// Utility.setStringPreference(getParent(), "LoginToken",
				// Result);
				System.out.println("Parse Result");
				parse_Inbox(Result);

			} else {
				// Utility.printLog("Login Responce", "Login Unsuccessfully");
				// Toast.makeText(Password.this, repor.getMessage(),
				// Toast.LENGTH_SHORT).show();
			}

		}
	}

	public class GetDeliveryAcceptance extends AsyncTask<String, Void, Boolean> {
		boolean result = false;
		// String error_msg = "";
		String Result = null;
		Parser_Soap parse = new Parser_Soap();
		Error_Report repor = new Error_Report();

		protected Boolean doInBackground(String... params) {
			Http_Soap_Call call = Http_Soap_Call.create_connection("",
					getParent());
			if (call != null) {
				// Result = parse.GetLoginToken(
				// call.GetLoginToken(Username, params[0], repor), repor);
				Result = parse
						.GetDeliveryAcceptance(call.GetDeliveryAcceptance(
								params[0], params[1], repor), repor);
				if (Result != null) {
					result = true;

				} else {
					// error_msg=Utility.INVALID_USER;
					System.out.println("false");
					result = false;
					repor.setMessage("Internal Error");
				}

			} else {
				repor.setMessage(Utility.NETWORK_ISSUE);
				return false;
			}

			return result;
		}

		protected void onPreExecute() {
			pd = ProgressDialog.show(getParent(), null,
					getString(R.string.loader));
		}

		protected void onPostExecute(Boolean result) {
			// This method runs in the UI thread

			pd.dismiss();
			if (result) {
				// Utility.printLog("Login Responce", "Login successfully");
				// Utility.setStringPreference(getParent(), "LoginToken",
				// Result);
				System.out.println("Parse Result");
				parse_Delivery(Result);

			} else {
				// Utility.printLog("Login Responce", "Login Unsuccessfully");
				// Toast.makeText(Password.this, repor.getMessage(),
				// Toast.LENGTH_SHORT).show();
			}

		}
	}

	public void parse_Inbox(String jsonArray) {

		// {"ReturnValue":"[]"}

		try {

			if (jsonArray != null) {
				Bean_List.clear();
				call_other(jsonArray);
				/*
				 * if (jsonArray.contains("\"[")) { jsonArray =
				 * jsonArray.replace("\"[", "["); }
				 * 
				 * if (jsonArray.contains("]\"")) { jsonArray =
				 * jsonArray.replace("]\"", "]"); }
				 * 
				 * if (jsonArray.contains("\\")) { jsonArray =
				 * jsonArray.replace("\\", ""); }
				 * 
				 * JSONObject js = new JSONObject(jsonArray);
				 * 
				 * JSONArray aaray = js.getJSONArray("ReturnValue");
				 * 
				 * for (int i = 0; i < aaray.length(); i++) { Message_Bean bean
				 * = new Message_Bean(); JSONObject jobj =
				 * aaray.getJSONObject(i);
				 * bean.setDateAndTime(jobj.getString("DateAndTime"));
				 * System.out.println(jobj.getString("DateAndTime"));
				 * bean.setDescription(jobj.getString("Description"));
				 * bean.setAttachments(jobj.getString("Attachments"));
				 * bean.setSender(jobj.getString("Sender"));
				 * bean.setStatus(jobj.getString("Status"));
				 * bean.setUniq_guid(jobj.getString("_uniq_guid"));
				 * bean.setMsg_guid(jobj.getString("_msg_guid"));
				 * bean.setActions(jobj.getString("Actions"));
				 * Bean_List.add(bean); }
				 */
				System.out.println("Bean_List" + Bean_List.size());
				adapter.notifyDataSetChanged();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void call_other(String jsonArray) {
		try {
			Object obj = JSONValue.parse(jsonArray);
			org.json.simple.JSONObject jobj = (org.json.simple.JSONObject) obj;

			System.out.println("ggg" + jobj.get("ReturnValue"));

			Object obj1 = JSONValue.parse((String) jobj.get("ReturnValue"));

			org.json.simple.JSONArray array = (org.json.simple.JSONArray) obj1;

			for (int i = 0; i < array.size(); i++) {

				org.json.simple.JSONObject jobj1 = (org.json.simple.JSONObject) array
						.get(i);

				System.out.println("HHH" + jobj1.get("DateAndTime"));
				Message_Bean bean = new Message_Bean();
				bean.setDateAndTime(jobj1.get("DateAndTime") + "");
				bean.setDescription(jobj1.get("Description") + "");
				bean.setAttachments(jobj1.get("Attachments") + "");
				bean.setSender(jobj1.get("Sender") + "");
				bean.setStatus(jobj1.get("Status") + "");
				bean.setUniq_guid(jobj1.get("_uniq_guid") + "");
				bean.setMsg_guid(jobj1.get("_msg_guid") + "");
				bean.setActions(jobj1.get("Actions") + "");
				Bean_List.add(bean);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	public void parse_Delivery(String result) {

		if (result != null) {
			try {
				Deliver_Beans beans = new Deliver_Beans();
				JSONArray aaray = new JSONArray(result);
				for (int i = 0; i < aaray.length(); i++) {

					JSONObject jobj = aaray.getJSONObject(i);

					beans.setSender(jobj.getString("Sender"));
					beans.setYourName(jobj.getString("YourName"));
					beans.setYourEmail(jobj.getString("YourEmail"));
					beans.setErrorMessage(jobj.getString("ErrorMessage"));

					beans.setRequireFP(jobj.getBoolean("RequireFP"));
					beans.setRequireAC(jobj.getBoolean("RequireAC"));
					beans.setRequireES(jobj.getBoolean("RequireES"));

					beans.setMsg_UID(MSG_ID);
					System.out.println("position" + position);
					System.out.println("position"
							+ Bean_List.get(position).getActions());
					if (position != -1) {
						if (Bean_List.get(position).getActions().equals("T")) {
							beans.setPending_Accepted(true);
						} else if (Bean_List.get(position).getActions()
								.equals("V")) {
							beans.setPending_Accepted(false);
						}

					}

				}
				Intent intent = new Intent(getParent(), Message_Viewer.class);
				intent.putExtra("bean", beans);
				((TabBaseGroupActivity) getParent()).startChildActivity(
						Message_Viewer.class.getSimpleName(), intent);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}
